package com.dckeji.shiplock.framework.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.protocol.HTTP;

/**
 * Created with IntelliJ IDEA.
 * User: TianWei
 * Date: 2017/8/12
 * Time: 14:13
 */
public class SingleAccessToken {

    private WeChatConf weChatConf;
    private static SingleAccessToken singleAccessToken;

    /**
     * 私有构造函数
     */
    private SingleAccessToken(String tokenUrl, String tiketUrl) {
        String tokenJson = HttpClientUtil.getInstance().sendData4GetHTTPS(tokenUrl);
        JSONObject token = JSON.parseObject(tokenJson);
        weChatConf = new WeChatConf();
        weChatConf.setTokenExpiresIn(token.getInteger("expires_in"));
        weChatConf.setToken(token.getString("access_token"));

        String tiketJson = HttpClientUtil.getInstance()
                .sendData4GetHTTPS(tiketUrl.replace("ACCESS_TOKEN", weChatConf.getToken()));
        JSONObject tiket = JSONObject.parseObject(tiketJson);
        weChatConf.setTicket(tiket.getString("ticket"));
        weChatConf.setTicketExpiresIn(tiket.getInteger("expires_in"));

        initThread();
    }


    /**
     * 获取SingleAccessToken对象
     *
     * @return
     */
    public static SingleAccessToken getInstance(String url, String tiketUrl) {
        if (singleAccessToken == null) {
            singleAccessToken = new SingleAccessToken(url, tiketUrl);
        }
        return singleAccessToken;
    }

    public WeChatConf getAccessToken() {
        return weChatConf;
    }

    public void setAccessToken(WeChatConf weChatConf) {
        this.weChatConf = weChatConf;
    }

    /**
     * 开启线程，设置SingleAccessToken为空
     */
    private void initThread() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    //睡眠7000秒
                    Thread.sleep(7000 * 1000);
                    singleAccessToken = null;

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();
    }


}
